using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UserSurface;
using ApplicationCore;
using System.Diagnostics;
using System.Deployment.Application;
using System.Threading;
using ComponentFactory.Krypton.Toolkit;
using System.Linq;
using ComponentFactory.Krypton.Navigator;


namespace EnzymeLaborTool
{
    public partial class MainForm : KryptonForm
    {
        private bool connected = false;
        private MainSurface ms;
        public MainForm()
        {
            ms = new MainSurface(this);

            LoginDlg l = new LoginDlg();

            while (!connected)
            {
                l.ShowDialog();
                if (l.DialogResult != DialogResult.OK)
                {
                    break;
                }
                connected = ms.Connect(l.user, l.pass);
                if (!connected)
                    MessageBox.Show("Login failed", "Login error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            InitializeComponent();
            //decimalsNumericUpDown.Value = Properties.Settings.Default.exportDecimals;
            //interBatchCenteCheckButton.Checked = Properties.Settings.Default.ApplyIBC;
            //replicaMergeCheckButton.Checked = Properties.Settings.Default.AliquotMerge;

            //if (connected)
            //    ApplySecurity();

            //ms.ExportProgress += new EventHandler<ProgressEventArgs>(ms_ExportProgress);

        }

        //void ms_ExportProgress(object sender, ProgressEventArgs e)
        //{
        //    //this.exportProgressBar.Value = e.Progress;

        //    Label.CheckForIllegalCrossThreadCalls = false;
        //    this.exportProgressLabel.Text = e.MainStep + "   " + e.SubStep;
        //    this.exportProgressLabel.Update();
        //}

        private void Form1_Load(object sender, EventArgs e)
        {
            if (connected)
            {
                _lastPage = kryptonNavigatorMain.SelectedPage;
                enzymeStandardsCtrl.Init(ms);

                exportCtrl1.Init(ms);
                freshWeightCtrl.Init(ms);

                //   bindingSource1.DataSource = ms.Data;

                //  bindingSource1.CurrentChanged += new EventHandler(On_LoadExportData);
                batchCtrl.StatusChanged += new EventHandler<StatusChangedEventArgs>(batchCtrl_StatusChanged);

            }
        }

        private KryptonPage _lastPage;
        private void kryptonNavigatorMain_SelectedPageChanged(object sender, EventArgs e)
        {
            try
            {
                if (kryptonNavigatorMain.SelectedPage == kryptonPageFreshweights)
                {
                    freshWeightCtrl.Activate();
                }
                if (kryptonNavigatorMain.SelectedPage == kryptonPageBatches)
                {
                    batchCtrl.Init(ms);
                    if (_lastPage == kryptonPageRawdata)
                    {
                        batchCtrl.NavigateToBatch(processingCtrl.SearchTerm, processingCtrl.SelectedBatch);
                    }
                    else
                    {
                        batchCtrl.InvalidateDataContext();
                    }
                }
                if (kryptonNavigatorMain.SelectedPage == kryptonPageRawdata)
                {
                    processingCtrl.Init(ms);
                    if (_lastPage == kryptonPageBatches)
                    {
                        processingCtrl.NavigateToBatch(batchCtrl.SearchTerm, batchCtrl.SelectedBatch);
                    }
                    else
                    {
                        processingCtrl.InvalidateDataContext();
                    }
                }

                _lastPage = kryptonNavigatorMain.SelectedPage;
            }
            catch (Exception ex)
            {
                Microsoft.SqlServer.MessageBox.ExceptionMessageBox box = new Microsoft.SqlServer.MessageBox.ExceptionMessageBox(ex);
                box.Show(this);
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoginDialog ab = new LoginDialog();
            ab.ShowDialog();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.Close();
        }


        private bool firstTabPageBatchEnter = true;
        private void tabPageBatches_Enter(object sender, EventArgs e)
        {
            //TODO:navigation between batches an raw data
        }


        //#region Tab Processing


        //private void tabPageRawDataProcessing_Enter(object sender, EventArgs e)
        //{
        //    //TODO: nav between batches and rawdata

        //}



        //#endregion


        //private void experimentsExportBindingSource_CurrentChanged(object sender, EventArgs e)
        //{

        //    //if (tabControlMain.SelectedTab == tabPageExport)
        //    //{
        //    //    try
        //    //    {
        //    //this.Cursor = Cursors.WaitCursor;
        //    if (bindingSource1.Current != null)
        //    {

        //        EnzymeProcessingDataSet.ExperimentsRow r = (bindingSource1.Current as DataRowView).Row as EnzymeProcessingDataSet.ExperimentsRow;
        //        if (r != null)
        //        {
        //            //kryptonHeaderGroup1.Text = "Export " +  r.Id;

        //            //exportDataGridView.DataSource = null;
        //            //exportProgressBar.Visible = true;

        //            //exportLoadBackgroundWorker.RunWorkerAsync();
        //            //On_ExportOptionsChanged(null, null);
        //            //if(interBatchCenteringCheckBox.Checked)
        //              //  exportDataGridView.DataSource = ms.NavigateExportExperiment(r, PostProcessorOption.InterBatchCentering);
        //            //else
        //            //    exportDataGridView.DataSource = ms.NavigateExportExperiment(r, PostProcessorOption.None);


        //            //foreach (DataGridViewColumn dc in exportDataGridView.Columns)
        //            //{
        //            //    dc.DefaultCellStyle.NullValue = "NA";
        //            //    dc.DefaultCellStyle.Format = "N2";
        //            //}

        //            //exportDataGridView.Sort(exportDataGridView.Columns[2], ListSortDirection.Ascending);
        //        }
        //        //    }
        //        //}
        //        //catch (Exception ex)
        //        //{
        //        //    exportDataGridView.DataSource = new DataTable();
        //        //    MessageBox.Show(ex.Message);

        //        //}
        //        //finally
        //        //{
        //        //    this.Cursor = Cursors.Default;
        //        //    exportProgressBar.Visible = false;
        //        //}
        //    }
        //}

        //private void filterExperimentTextBox_TextChanged(object sender, EventArgs e)
        //{
        //    bindingSource1.Filter = "Id <> 'EB' and Material_Fk = 'none' and Id like '*" + filterExperimentTextBox.Text + "*'";
        //}

        private void Form1_Shown(object sender, EventArgs e)
        {
            kryptonPageStandards.Select();
            if (!connected)
                this.Close();
        }

        //private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    bindingSource1.SuspendBinding();

        //    ms.Refresh();

        //    bindingSource1.ResumeBinding();
        //}




        //private void On_LoadExportData(object sender, EventArgs e)
        //{
        //    if (kryptonNavigatorMain.SelectedPage == kryptonPageExportAlt)
        //    {

        //        EnableDisableExportControls(false);
        //        exportLoadBackgroundWorker.RunWorkerAsync();
        //    }

        //}


        //private void On_ExportOptionsChanged(object sender, EventArgs e)
        //{
        //    if (ms.CurrenPostProcessor != null && kryptonNavigatorMain.SelectedPage == kryptonPageExportAlt)
        //    {
        //        EnableDisableExportControls(false);
        //        exportBackgroundWorker.RunWorkerAsync();
        //    }

        //}

        //private DataTable LoadExportData()
        //{

        //        //this.exportProgressBar.Visible = true;
        //    int decimals = 2;// (int)decimalsNumericUpDown.Value;
        //        if (interBatchCenteCheckButton.Checked && replicaMergeCheckButton.Checked)
        //        {

        //            this.exportDataGridView.DataSource = ms.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.All, decimals);

        //        }
        //        else if (interBatchCenteCheckButton.Checked)
        //        {
        //            return ms.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.InterBatchCentering, decimals);
        //            //this.exportDataGridView.DataSource = ms.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.InterBatchCentering, decimals);
        //        }
        //        else if (replicaMergeCheckButton.Checked)
        //        {
        //            this.exportDataGridView.DataSource = ms.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.AliquotMerge, decimals);
        //        }
        //        else
        //        {
        //            this.exportDataGridView.DataSource = ms.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.None, decimals);

        //        }

        //        //this.exportProgressBar.Visible = false;
        //        //exportDataGridView.Sort(exportDataGridView.Columns[2], ListSortDirection.Ascending);

        //}

        //private void exportBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    //EnableDisableExportControls(false);
        //    BackgroundWorker bw = sender as BackgroundWorker;
        //    ProgressBar.CheckForIllegalCrossThreadCalls = false;
        //    int decimals = (int)decimalsNumericUpDown.Value;

        //    if (interBatchCenteCheckButton.Checked && replicaMergeCheckButton.Checked)
        //    {

        //        e.Result = ms.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.All, decimals, bw);

        //    }
        //    else if (interBatchCenteCheckButton.Checked)
        //    {
        //        e.Result = ms.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.InterBatchCentering, decimals, bw);
        //    }
        //    else if (replicaMergeCheckButton.Checked)
        //    {
        //        e.Result = ms.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.AliquotMerge, decimals, bw);
        //    }
        //    else
        //    {
        //        e.Result = ms.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.None, decimals, bw);

        //    }
        //}

        //private void exportBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    Debug.WriteLine("Post Processing beendet");

        //    this.exportDataGridView.DataSource = null;
        //    if (e.Error == null && !e.Cancelled)
        //    {

        //        this.exportDataGridView.DataSource = e.Result;
        //        exportDataGridView.Sort(exportDataGridView.Columns["Sample"], ListSortDirection.Ascending);
        //    }
        //    //else
        //    //    this.exportDataGridView.DataSource = null;

        //    this.exportProgressBar.Value = 0;
        //    this.exportProgressLabel.Text = "";
        //    EnableDisableExportControls(true);
        //}

        //private void exportBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        //{
        //    if (e.ProgressPercentage - lastProgress > 3 || e.ProgressPercentage == 0)
        //    {
        //        this.exportProgressBar.Value = e.ProgressPercentage;
        //        this.exportProgressLabel.Text = e.UserState as string;
        //        //Application.DoEvents();
        //        this.exportProgressLabel.Update();
        //    }

        //}

        //private void exportLoadBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    if (bindingSource1.Current != null)
        //    {

        //        EnzymeProcessingDataSet.ExperimentsRow r = (bindingSource1.Current as DataRowView).Row as EnzymeProcessingDataSet.ExperimentsRow;
        //        if (r != null)
        //        {
        //            //EnzymeProcessingDataSet.ExperimentsRow r = (bindingSource1.Current as DataRowView).Row as EnzymeProcessingDataSet.ExperimentsRow;

        //            //TODO:KRYPTON
        //            //kryptonHeaderGroup1.Text = "Export " + r.Id;
        //            //ms.NavigateExportExperiment(r, sender as BackgroundWorker);
        //        }
        //    }
        //}

        //private void exportLoadBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    Debug.WriteLine("LoadData beendet");
        //    lastProgress = 0;
        //    this.exportProgressBar.Value = 0;
        //    this.exportProgressLabel.Text = "";
        //    if (e.Error == null && !e.Cancelled)
        //    {
        //        Debug.WriteLine("Starte jetzt post processing");
        //        //On_ExportOptionsChanged(null, null);
        //        exportBackgroundWorker.RunWorkerAsync();
        //    }
        //    else
        //    {
        //        EnableDisableExportControls(true);
        //        this.exportDataGridView.DataSource = null;
        //    }


        //}

        //private int lastProgress = 0;
        //private void exportLosBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        //{
        //    if (e.ProgressPercentage - lastProgress > 3)
        //    {
        //        lastProgress = e.ProgressPercentage;
        //        this.exportProgressBar.Value = e.ProgressPercentage;
        //        this.exportProgressLabel.Text = e.UserState as string;
        //        this.exportProgressLabel.Update();
        //    }
        //}

        //private void EnableDisableExportControls(bool val)
        //{
        //    NumericUpDown.CheckForIllegalCrossThreadCalls = false;
        //    KryptonCheckButton.CheckForIllegalCrossThreadCalls = false;
        //    DataGridView.CheckForIllegalCrossThreadCalls = false;

        //    decimalsNumericUpDown.Enabled = val;
        //    interBatchCenteCheckButton.Enabled = val;
        //    replicaMergeCheckButton.Enabled = val;
        //    this.dataGridView2.Enabled = val;
        //    //this.cancelExportButton.Visible = !val;
        //    this.exportProgressBar.Visible = !val;


        //    NumericUpDown.CheckForIllegalCrossThreadCalls = true;
        //    KryptonCheckButton.CheckForIllegalCrossThreadCalls = true;
        //    DataGridView.CheckForIllegalCrossThreadCalls = true;
        //    Application.DoEvents();
        //}

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.Save();
        }

        private void databaseStatisticsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StatisticsForm st = new StatisticsForm(this.ms);
            st.Show();
        }

        //private void dataGridView2_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        //{
        //    DataGridView dgv = sender as DataGridView;
        //    if ((string)dgv.Rows[e.RowIndex].Cells[1].Value != "none")
        //        e.CellStyle.BackColor = Color.Green;

        //}

        //private void checkBoxShowControls_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (checkBoxShowControls.Checked)
        //        bindingSource1.Filter = "Id <> '?'  and Id <> 'EB'";
        //    else
        //        bindingSource1.Filter = "Id <> '?'  and Id <> 'EB' and Material_Fk = 'none'";
        //}


        private void kryptonNavigatorMain_Selecting(object sender, ComponentFactory.Krypton.Navigator.KryptonPageCancelEventArgs e)
        {
            if (kryptonNavigatorMain.SelectedPage == kryptonPageBatches)
            {
                e.Cancel = !batchCtrl.AllowNavigation();
            }
        }


        void batchCtrl_StatusChanged(object sender, StatusChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.status))
            {
                System.Timers.Timer t = new System.Timers.Timer(5000d);
                t.Start();
                t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
                toolStripStatusLabel1.Tag = t;
            }
            else
            {
                toolStripStatusLabel1.Tag = null;
            }

            toolStripStatusLabel1.Text = e.status;
        }

        void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            System.Timers.Timer t = sender as System.Timers.Timer;
            if (t.Equals(toolStripStatusLabel1.Tag as System.Timers.Timer))
            {
                toolStripStatusLabel1.Tag = null;
                this.Invoke((MethodInvoker)delegate { toolStripStatusLabel1.Text = string.Empty; });
            }

            t.Stop();
            t.Dispose();
        }
    }
}